<script setup>
import { userUpdatePasswordService } from '@/api/user'
import { useUserStore } from '@/stores'

const formModel = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度在6到15个非空格字符',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度在6到15个非空格字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === formModel.value.old_pwd) {
          callback(new Error('原密码和新密码不能一样!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  re_pwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码长度在6到15个非空格字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.new_pwd) {
          callback(new Error('两次输入的密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
// 修改密码
const editPwd = async () => {
  // 校验表单
  const valid = formRef.value.validate()
  if (valid) {
    await userUpdatePasswordService(formModel.value)
    ElMessage.success('修改密码成功')
    userStore.removeToken()
    userStore.removeUser()
    router.push('/login')
  }
}
// 重置密码
const resetPwd = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <page-container title="重置密码">
    <el-row>
      <el-col :span="12">
        <el-form
          ref="formRef"
          :model="formModel"
          label-width="100px"
          :rules="rules"
          size="large"
        >
          <el-form-item prop="old_pwd" label="原密码">
            <el-input v-model="formModel.old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item prop="new_pwd" label="新密码">
            <el-input v-model="formModel.new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item prop="re_pwd" label="确认新密码">
            <el-input v-model="formModel.re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editPwd">修改密码</el-button>
            <el-button @click="resetPwd">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>
